/**
 * 系统附件管理初始化
 */
var Sessions = {
    id: "SessionsTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    refreshIntervalId:null,
    refreshDelay:5000,
    oldSelections:null,
    oldData:null
};

/**
 * 初始化表格的列
 */
Sessions.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
            {field: 'id', visible: false },
            {title: '登录名', field: 'attributes.shiroUser.account', visible: true, align: 'left', valign: 'middle', sortable: true},
            {title: '用户', field: 'attributes.shiroUser.name', visible: true, align: 'left', valign: 'middle', sortable: true},
            {title: '部门', field: 'attributes.shiroUser.deptName', visible: true, align: 'left', valign: 'middle', sortable: true},
            {title: '开始时间', field: 'startTimestamp', visible: true, align: 'center', valign: 'middle',formatter:Sessions.datetimeToStr, sortable: true},
            {title: '最后访问时间', field: 'lastAccessTime', visible: true, align: 'center', valign: 'middle',formatter:Sessions.datetimeToStr, sortable: true},
            {title: '登录点', field: 'attributes.loginPath', visible: true, align: 'left', valign: 'middle', sortable: true},
            {title: '网络地址', field: 'host', visible: true, align: 'left', valign: 'middle', sortable: true},
            {title: 'UserAgent', field: 'attributes', visible: true, align: 'left', valign: 'middle',events:{
                "mouseover .userAgent":function(e,value){
                    $(e.target).popover({
                        content:value.userAgent,
                        placement:'top'
                    }).popover('show');
                },
                "mouseout .userAgent":function(e){
                    $(e.target).popover("hide");
                }
            },formatter:function(value){
                if(!value ||!value.userAgent)
                    return null;
                var userAgent = value.userAgent;
                return "<div class='userAgent' role='button'  >"
                        + (userAgent.length>100?(userAgent.substring(0,100)+"..."):userAgent) 
                        + "</div>";
            }, sortable: true},
            {title: '过期时间', field: 'stopTimestamp', visible: true, align: 'center', valign: 'middle',formatter:Sessions.datetimeToStr, sortable: true}
    ];
};
Sessions.datetimeToStr = function(time){
    function padding(val){
        return ""+(val>9?val:("0"+val));
    }
    if(!time)
        return null;
	var date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth();
    var day = date.getDate();
    var hours = date.getHours();
    var mins = date.getMinutes();
    var secs = date.getSeconds();
    return ""+year+"-"+padding(month+1)
            +"-"
            +padding(day)
            +" "
            +padding(hours)
            +":"
            +padding(mins)
            +":"
            +padding(secs);
}

/**
 * 检查是否选中
 */
Sessions.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Feng.info("请先选中表格中的某一记录！");
        return false;
    }else{
        Sessions.seItem = selected[0];
        return true;
    }
};


/**
 * 打开查看系统附件详情
 */
Sessions.openSessionsDetail = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '会话详情',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/Sessions/Sessions_update/' + Sessions.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 删除系统附件
 */
Sessions.delete = function () {
    if (this.check() ) {
    	Feng.confirm("停止会话会影响当前访问用户，请谨慎删除！",function(){
    		var ajax = new $ax(Feng.ctxPath + "/api/Sessions/remove?SessionsId="+Sessions.seItem.id, function (data) {
    			Feng.success("删除成功!");
    			Sessions.table.refresh();
    		}, function (data) {
    			Feng.error("删除失败!" + data.responseJSON.message + "!");
    		});
    		ajax.type="delete";
    		ajax.start();
    	});
    }
};

/**
 * 查询系统参数列表
 */
Sessions.search = function () {
	var condition =$("#condition").val();
	$.getJSON(Feng.ctxPath+"/api/account/sessions",function(res){
		Sessions.oldData = res.data;
        var newdata = Sessions.oldData.filter(function (e) { 
            if(!e.attributes || !e.attributes.shiroUser)
                return false;
            return e.attributes.shiroUser.account.toUpperCase().indexOf(condition.toUpperCase())>-1 
                || e.attributes.shiroUser.name.toUpperCase().indexOf(condition.toUpperCase())>-1 ; 
        });
        Sessions.table.btInstance.bootstrapTable("load", newdata);
	});
};
Sessions.toggleAutoRefresh = function (){
    var autoRefresh = $("#autoRefreshBtn").prop( "checked" );
    if(Sessions.refreshIntervalId){
        clearInterval(Sessions.refreshIntervalId);
    }
    if(autoRefresh){
        Sessions.table.refresh();
        Sessions.refreshIntervalId = setInterval(function(){
            Sessions.table.refresh();
        }, Sessions.refreshDelay);
    }
}
Sessions.refresh= function(){
    Sessions.table.refresh();
    if(Sessions.oldSelections){
        for(var i in Sessions.oldSelections){
            Sessions.table.btInstance.bootstrapTable("checkBy",{field:"id",values:[Sessions.oldSelections[i].id]});
        }
    }
}
$(function () {
    var defaultColunms = Sessions.initColumn();
    var table = new BSTable(Sessions.id, "/api/account/sessions", defaultColunms, function(res){
        Sessions.oldData = res.data;
    	return res.data;
    });
    table.method="get";
    table.setPaginationType("client");
    Sessions.table = table.init();
    Sessions.table.btInstance.on("check.bs.table",function(){
        Sessions.oldSelections = Sessions.table.btInstance.bootstrapTable('getSelections');
    });
    Sessions.table.btInstance.on("reset-view.bs.table",function(){
        if(Sessions.oldSelections){
            for(var i in Sessions.oldSelections){
                Sessions.table.btInstance.bootstrapTable("checkBy",{field:"id",values:[Sessions.oldSelections[i].id]});
            }
        }
    });
});
